package cn.ctodb.commons.file.client;

import java.io.IOException;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;

public class FastdfsClient extends ObjectStorage {

	private TrackerClient tracker;

	@Override
	protected void init() {
		super.init();
		ClientGlobal.setG_charset("UTF-8");
		tracker = new TrackerClient();
	}

	public String upload(byte[] fileContent, NameValuePair[] metaData, String prefix) throws Exception {
		if (null == fileContent || null == prefix)
			throw new Exception("FDFSClient invalid arguement");

		TrackerServer trackerServer = null;
		StorageClient1 storageClient = null;

		String master_file_id = null;
		try {
			trackerServer = tracker.getConnection();
			StorageServer storageServer = null;
			storageClient = new StorageClient1(trackerServer, storageServer);

			master_file_id = storageClient.upload_file1(fileContent, prefix, metaData);
		} finally {
			if (trackerServer != null) {
				trackerServer.close();
			}
		}
		return master_file_id;
	}

	/**
	 * 删除文件（注意tracker对应的nginx下的缓存）
	 * 
	 * @param fileId
	 *            上传时候返回的路径即为唯一标示
	 * @return 删除是否成功标志
	 */
	@Override
	public void delete(String fileId) throws IOException {
		TrackerServer trackerServer = null;
		StorageClient1 storageClient = null;
		try {
			trackerServer = tracker.getConnection();
			StorageServer storageServer = null;
			storageClient = new StorageClient1(trackerServer, storageServer);
			storageClient.delete_file1(fileId);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (trackerServer != null) {
				trackerServer.close();
			}
		}
	}

	@Override
	public byte[] load(String fileid) throws IOException {
		TrackerServer trackerServer = null;
		StorageClient1 storageClient = null;
		try {
			trackerServer = tracker.getConnection();
			StorageServer storageServer = null;
			storageClient = new StorageClient1(trackerServer, storageServer);
			return storageClient.download_file1(fileid);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (trackerServer != null) {
				trackerServer.close();
			}
		}

		return null;
	}

	@Override
	public String save(byte[] bytes, String extName) throws IOException {
		try {
			return upload(bytes, (NameValuePair[]) null, extName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
